package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.USER_FOLLOW_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IUserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key = USER_FOLLOW_KEY + userId;
        if (Boolean.TRUE.equals(isFollow)) {
            // 2.1 关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);

            boolean isSuccess = this.save(follow);
            if (!isSuccess) {
                return Result.fail("关注失败");
            }
            stringRedisTemplate.opsForSet().add(key, followUserId.toString());

        } else {
            // 2.2 取关，删除数据
            LambdaQueryWrapper<Follow> qw = new LambdaQueryWrapper<>();
            qw.eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId);
            boolean removed = this.remove(qw);
            if (!removed) {
                return Result.fail("取关失败");
            }
            stringRedisTemplate.opsForSet().remove(key, followUserId.toString());

        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        // 2.查询是否关注
        LambdaQueryWrapper<Follow> qw = new LambdaQueryWrapper<>();
        qw.eq(Follow::getUserId, userId).eq(Follow::getFollowUserId, followUserId);
        int count = this.count(qw);

        return Result.ok(count > 0);
    }

    @Override
    public Result followCommons(Long id) {
        // 1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key1 = USER_FOLLOW_KEY + userId;
        String key2 = USER_FOLLOW_KEY + id;
        // 2.求交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);
        if (intersect == null || intersect.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 3.解析id
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        // 4.查询用户
        List<User> users = userService.listByIds(ids);
        // 5.返回userDto
        List<UserDTO> userDTOS = users.stream()
                .map(u -> BeanUtil.copyProperties(u, UserDTO.class))
                .collect(Collectors.toList());

        // 合并两个流为一个流
        // List<UserDTO> userDTOList = intersect.stream().map(Long::valueOf)
        //         .map(t -> userService.getById(t))
        //         .map(u -> BeanUtil.copyProperties(u, UserDTO.class))
        //         .collect(Collectors.toList());

        return Result.ok(userDTOS);
    }
}
